golang http请求

golang用net/http包来发出http请求,日常最常用的是get和post

get方法

最直观的用法

1
2
3
4
5
6
7
8
9
10
11
12
resp, err := http.Get("http://example.com/restUrl")
if err != nil {
// handle error
}

defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}

fmt.Println(string(body))

但是如果url中有空格怎么办比如

1
http://example.com/query?q=hello world

这种情况下就需要net/url包,url包有专门的url类型

1
2
3
4
5
6
7
8
9
10
11
type URL struct {
Scheme string
Opaque string // encoded opaque data
User *Userinfo // username and password information
Host string // host or host:port
Path string
RawQuery string // encoded query values, without '?'
Fragment string // fragment for references, without '#'
}
对应的url结构为:
scheme://[userinfo@]host/path[?query][#fragment]

我们需要的就是query的部分

1
2
3
4
5
6
7
8
9
10
v := url.Values{}
v.Set("name", "Ava")
v.Add("friend", "Jess")
v.Add("friend", "Sarah")
v.Add("friend", "Zoe")
// v.Encode() == "name=Ava&friend=Jess&friend=Sarah&friend=Zoe"
v.Set("q","hello world")
u,_:=url.Parse("http://www.google.com/query?")
u.RawQuery = v.Encode()
fmt.Println(u.String())

url.Values定义了一个map[string]interface{},set方法能够设定key/value对,url.Encode()方法实现了把map转换成url的方法,然后将该encode值放入Url结构的RawQuery中就得到一个完整的url

##post请求

1
func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error)

bodyType为指定的数据请求类型,常见的有plain/text, application/json, plain/css, image/jpeg等
body为io.Reader,

1
bufio.NewReader("q=google")

就建立了一个io.Reader